//
// Created by Andrea Petreti on 27/10/2021.
//

#include "DocumentFile.h"
#include "android-log.h"

std::mutex DocumentFile::lockInitLibrary;
int DocumentFile::libraryReferenceCount = 0;

void DocumentFile::initLibraryIfNeeded() {
    std::lock_guard<std::mutex> lock(lockInitLibrary);
    if (libraryReferenceCount == 0) {
        LOGD("Init native FPDF library");
        FPDF_InitLibrary();
    }
    libraryReferenceCount++;
}

void DocumentFile::destroyLibraryIfNeeded() {
    std::lock_guard<std::mutex> lock(lockInitLibrary);
    libraryReferenceCount--;
    if (libraryReferenceCount == 0) {
        LOGD("Destroy native FPDF library");
        FPDF_DestroyLibrary();
    }
}

DocumentFile::DocumentFile() {
    DocumentFile::initLibraryIfNeeded();
}

DocumentFile::~DocumentFile() {
    if (pdfDocument != NULL) {
        FPDF_CloseDocument(pdfDocument);
    }

    DocumentFile::destroyLibraryIfNeeded();
}
